// zd_searchGroup
package Network

import (
	"SQL/db"
	"logs"
)

func searchGroup(clientID string, args interface{}) (response *ServerResponse) {
	code := Success
	msg := ""
	var res interface{}
	defer func() {
		if code != Success {
			logs.Print("code: ", code, " msg: ", msg)
		}
		response = &ServerResponse{
			Method:  "/searchGroup",
			Code:    code,
			Message: msg,
			Result:  res,
		}
	}()
	Args, ok := args.(map[string]interface{})
	if !ok {
		code = errAssertType
		msg = "type isn't map[string]interface{}"
		return
	}
	searchParam, ok := Args["searchParam"].(string)
	if !ok {
		code = errSearchParam
		msg = "searchParam error"
		return
	}
	if searchParam == "" {
		code = errSearchParam
		msg = "searchParam is null"
		return
	}
	msg, code, res = searchGroupOnDB(searchParam)
	return
}

func searchGroupOnDB(searchparam string) (msg string, code int, res interface{}) {
	/*sql := `select o.id,o.nickname,o.iconurl
	from objects o,groups g
	where o.id = g.id
		and (o.custom ->'公告' ? $1
		or o.custom ->'类型' ? $1
		or o.custom ->'地址' ? $1
		or o.custom ->'网站' ? $1
		or o.custom ->'群介绍' ?$1
		or o.Nickname = $1)`*/
	sql := `SELECT o.id,o.nickname,o.iconurl
		FROM objects o,groups g,(select id
			,CAST(custom ->'公告' AS character varying(500)) announcement
			,CAST(custom ->'类型' AS character varying(500)) typesof
			,CAST(custom ->'地址' AS character varying(500)) address
			,CAST(custom ->'网站' AS character varying(500)) website
			,CAST(custom ->'群介绍' AS character varying(500)) introduction 
			FROM objects) c
			WHERE o.id = g.id
				AND o.id = c.id
				AND (c.announcement like $1 
					OR c.typesof like $1 
					OR c.address like $1 
					OR c.website like $1 
					OR c.introduction like $1 
					OR o.nickname like $1);`

	searchparam = "%" + searchparam + "%"
	rows, err := db.RowQuery(sql, searchparam)
	if err != nil {
		logs.Print("searchGroup db.RowQuery failed", err.Error())
		code = errDBQueryFailed
		msg = err.Error()
		return
	}
	defer rows.Close()
	var gid, gnickname, giconurl string
	var groups []group
	var count = 0
	for rows.Next() {
		count++
		err = rows.Scan(&gid, &gnickname, &giconurl)
		if err != nil {
			logs.Print("searchGroup db.RowScan failed", err.Error())
			code = errRowsScan
			msg = err.Error()
			return
		}
		tem := &group{GroupID: gid, Nickname: gnickname, GroupIcon: giconurl}
		groups = append(groups, *tem)
	}
	if count == 0 {
		code = errGroupIDNotExist
		msg = "没有找到符合条件的群组"
		return
	}
	res = groups
	return "Success", Success, res
}
